<?php


namespace apps\marriage\app\mp\controller;


use apps\marriage\core\model\CourseOrder;
use apps\marriage\core\service\CourseOrderService;
use apps\marriage\core\service\CourseService;
use think\Exception;
use think\Request;

class CourseController extends BaseMarriageMpController
{
    /**
     * @var CourseService
     */
    private $courseService;

    /**
     * @var CourseOrderService
     */
    private $courseOrderService;

    protected function init()
    {
        parent::init();
        $this->courseService = service('Course', SERVICE_NAMESPACE);
        $this->courseOrderService = service('CourseOrder', SERVICE_NAMESPACE);
    }

    public function lists(Request $request)
    {
        $pageSize = $request->param('page_size', 10);
        $params = [
            'is_sale' => 1
        ];
        $res = $this->courseService->pageListByParams($params, $pageSize);
        if ($res['data']) {
            foreach ($res['data'] as &$rs) {
                $rs = $this->courseService->format($rs);
            }
        }
        return $this->success($res);
    }

    public function info(Request $request)
    {
        $id = $request->param('id', 0, 'intval');
        $course = $this->courseService->getByPk($id);
        if ($course['is_sale'] == 0) {
            throw new Exception('该课程已下线');
        }
        $course = $this->courseService->format($course);
        $joined = false;
        if ($this->user && $this->courseOrderService->info([
                'user_id' => $this->user['id'],
                'course_id' => $id,
                'pay_status' => CourseOrder::PAY_STATUS_PAIED
            ])) {
            $joined = true;
        }
        return $this->success([
            'course' => $course,
            'joined' => $joined
        ]);
    }

    public function share_poster(Request $request)
    {
        $courseId = $request->param('course_id');
        $fromuid = $request->param('fromuid');
        $url = $this->courseService->getSharePoster($courseId, $fromuid);
        return $this->success([
            'url' => $url
        ]);
    }

    public function sign_in(Request $request)
    {
        $id = $request->param('id', 0, 'intval');
        $course = $this->courseService->getByPk($id);
        if(empty($course)) {
            throw new Exception('课程不存在');
        }
        $course = $this->courseService->format($course);
        $joined = false;
        if($this->courseOrderService->info([
            'user_id' => $this->user['id'],
            'course_id' => $id
        ])) {
            $joined = true;
        }
        return $this->success([
            'course' => $course,
            'joined' => $joined
        ]);
    }
}